<script setup>
import { ref, reactive, getCurrentInstance, onMounted } from "vue";
import { ElMessage, ElMessageBox } from 'element-plus'
import SearchBar from "./conmponents/search.vue";
import tableDome from "./conmponents/tableDome.vue";
const searchDate = ref({
    keyword: "",
    placeholder: '请输入你要查询的关键字',
    Options: [
        { label: "全部", value: "0" },
        { label: "启用", value: "1" },
        { label: "禁用", value: "2" },
    ],
    selectedValue: "0",
});
// 这里是挂载到proxy实例的上边，可以实现全局调用
const { proxy } = getCurrentInstance()
//其中total是数据总条数，page是当前的页数，设置name根据name进行条件搜索
const config = reactive({
    // 当前的页数
    pagenum: 1,
    // 当前每页显示多少条数据
    pagesize: 10,
    // 总页数
    total: 0,
    status: '1',
    searchKey: ''
})
const id = ref('')
// 发布时间只能在今天以及今天之后
const pickerOptionsAdd = {
    disabledDate(time) {
        return time.getTime() < Date.now() - 24 * 60 * 60 * 1000
    }
}
const listData = ref([])
const columns = reactive([
    {
        prop: "id",
        label: "序号",
        width: 70,
        sortable: false
    },
    {
        prop: "content",
        label: "公告内容",
        width: 200,
        sortable: false,
    },
    {
        prop: "publish_date",
        label: "发布日期",
        width: 200,
        sortable: false
    },
    {
        prop: "status",
        label: "状态",
        width: 80,
        sortable: false
    },
    {
        prop: "operator",
        label: "操作人",
        sortable: false,
        width: 200,
    },
    {
        prop: "operate_time",
        label: "操作时间",
        width: 400,
        sortable: false
    },
])
// 列表 
const getUserData = () => {
    console.log('config',searchDate.value);
    config.searchKey = searchDate.value.keyword
    proxy.$api.NoticeList(config).then(res => {
        console.log('res',res);
        
        listData.value = res.content
        config.total = res.total
    })
    console.log('congig',config.total);
    
}
onMounted(() => {
    getUserData()
})
const onSubmit = () => {
    console.log('submit!')
    getUserData()
}
const currentRow = ref({})
const editDialogVisible = ref(false)
// 编辑
const handleEdit = (row) => {
    id.value = row.id
    currentRow.value = { ...row }; // 创建当前行的副本以进行编辑  
    if (currentRow.value.status === '启用') {
        currentRow.value.radioEdit = '1'
    } else {
        currentRow.value.radioEdit = '2'
    }
    editDialogVisible.value = true; // 打开编辑对话框  
}
// 编辑 ===> 确定
const editListConfirm = () => {
    var operate_time = new Date().format('yyyy-MM-dd hh:mm:ss')
    if (currentRow.value.radioSta === '1') {
        currentRow.value.status = '启用'
    } else {
        currentRow.value.status = '禁用'
    }
    console.log('id',id);
    const promis = {
            content: currentRow.value.content,
            publish_time: currentRow.value.publish_time,
            status: currentRow.value.status,
            operate_time: operate_time
        }
        
    if (id.value) {
        proxy.$api.editNoticeList(promis)

        ElMessage({ showClose: true, message: '编辑公告成功！', type: 'success' })
    } else {
        proxy.$api.addNoticeList({
            content: currentRow.value.content,
            publish_date: currentRow.value.publish_date,
            status: currentRow.value.status,
            operate_time: operate_time
        })
        ElMessage({ showClose: true, message: '添加公告成功！', type: 'success' })
    }
    getUserData()
    editDialogVisible.value = false; // 打开编辑对话框  
    //获取到表单dom，执行resetFields重置表单
    proxy.$refs["userForm"].resetFields()
    //   if (response.code != 200) {
    //     this.$message.error('添加公告失败！')
    //   } else {
    //     this.$message.success('添加公告成功！')
    //   }
    //   getUserData()

}
// 日期格式
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1, //月份
        "d+": this.getDate(), //日
        "h+": this.getHours() % 12 == 0 ? 12 : this.getHours() % 12, //小时
        "H+": this.getHours(), //小时
        "m+": this.getMinutes(), //分
        "s+": this.getSeconds(), //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds() //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
}

// const formatDate = (date) => {  
//     const year = date.getFullYear();  
//     const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始  
//     const day = String(date.getDate()).padStart(2, '0');  
//     return `${year}-${month}-${day}`;  
// };  

// 新增
const handleAdd = () => {
    editDialogVisible.value = true; // 打开新增对话框  
}
// 删除
const handleDelete = (row) => {
    ElMessageBox.confirm("你确定要删除吗？").then(() => {
        proxy.$api.delNoticeList({ id: row.id })
        ElMessage({
            showClose: true,
            message: '删除成功',
            type: 'success'
        })
        getUserData()
    })
}
// 分页
const handleChange = (page) => {
    config.page = page
    getUserData()
}
</script>

<template>
  <div class="table">
        <el-row :gutter="20">
            <el-col :span="4"><el-button type="primary" @click="handleAdd">新增</el-button></el-col>
            <el-col :span="12"></el-col>
            <el-col :span="6">
                <SearchBar v-model="searchDate" :getUserData="getUserData"></SearchBar>
            </el-col>
            <el-col :span="1">
                <el-button type="primary" @click="onSubmit">
                    <el-icon style="vertical-align: middle">
                        <Search />
                    </el-icon>
                    <span style="vertical-align: middle"> 查询 </span>
                </el-button>
            </el-col>
        </el-row>
        <!-- 表格 -->
        <tableDome :tableData="listData" :columns="columns" @edit="handleEdit" @delete="handleDelete"></tableDome>
        <!-- 按钮 -->
        <el-pagination 
        class="pager"
        background 
        layout="prev, pager, next" 
        :total="config.total" size="small"
        @current-change="handleChange"
        />  
    </div>
    <el-dialog title="Edit Row" v-model="editDialogVisible">
        <!-- 内容主体区域 -->
        <el-form label-width="70px" :model="currentRow" ref="userForm">
            <el-form-item label="公告内容">
                <el-input v-model="currentRow.content" type="textarea" :rows="3"></el-input>
            </el-form-item>
            <el-form-item label="发布日期">
                <el-date-picker v-model="currentRow.publish_date" type="date" placeholder="选择日期" ormat="YYYY/MM/DD"
                    value-format="YYYY-MM-DD" :picker-options="pickerOptionsAdd" />
            </el-form-item>
            <el-form-item label="状态">
                <el-radio v-model="currentRow.radioEdit" label="1">启用</el-radio>
                <el-radio v-model="currentRow.radioEdit" label="2">禁用</el-radio>
            </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <template #footer>
            <el-button @click="editDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editListConfirm()">确 定</el-button>
        </template>
    </el-dialog>
</template>

<style scoped lang="less">
.el-form--inline .el-form-item {
    margin-left: 20px;
    margin-right: 0px;
}
.table{
   position:relative;
   .pager{
      position:absolute;
      right:10px;
      bottom:10px;
   }
   .el-table{
      width:100%;
      height:500px;
   }
}
</style>
